package com.siss.tenancy.user.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 类名: FeignClientsConfigurationCustom.java
 * 描述: FeignClient拦截器 -微服务间传递header
 * 创建人: yingw
 * 创建时间: 2018年7月5日下午2:39:34
 */
@Configuration
@EnableFeignClients(basePackages = "com.siss.tenancy.user.client")
public class FeignClientsConfigurationCustom implements RequestInterceptor {
  //@Autowired
  //private ObjectMapper objectMapper;

  @Override
  public void apply(RequestTemplate template) {

    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes == null) {
      return;
    }

    HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
    Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames != null) {
      while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        Enumeration<String> values = request.getHeaders(name);
        while (values.hasMoreElements()) {
          String value = values.nextElement();
          if("Content-Type".equalsIgnoreCase(name) && value.indexOf("multipart/form-data") != -1){
            value = "application/json";
          }
          template.header(name, value);
        }
      }
    }
   /* TenantInfo entity = new TenantInfo();
    entity.setDbSchema(TenantContextHolder.getSchema());
    entity.setDbRedisIndex(TenantContextHolder.getRedisIndex());
    entity.setFilePath(TenantContextHolder.getFilePath());
    try {
      template.header("Tenant",objectMapper.writeValueAsString(entity)); //将租户信息传递到其他微服务
    } catch (JsonProcessingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }*/
  }

  private HttpServletRequest getHttpServletRequest() {
    try {
      return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    } catch (Exception e) {
      return null;
    }
  }

  /**
   * 获取原请求头
   */
  private Map<String, String> getHeaders(HttpServletRequest request) {
    Map<String, String> map = new LinkedHashMap<>();
    Enumeration<String> enumeration = request.getHeaderNames();
    if(enumeration!=null){
      while (enumeration.hasMoreElements()) {
        String key = enumeration.nextElement();
        String value = request.getHeader(key);
        map.put(key, value);
      }
    }
    return map;
  }

}
